const express = require('express');
const router = express.Router();
const pool = require('../pool.js');
const URL = require('url');
const http = require('http');
const request = require('request');

router.get('/handleCode',function(req, res, next){
	const params = URL.parse(req.url, true).query;
	console.log(params);

	//根据code获取网页授权access_token和openid
	const code = params.code;
	const appid = 'wx06c0a14577c208b3';
	const secret = 'c70fb7407b2f010933715a92837446e5';
	let url = `https://api.weixin.qq.com/sns/oauth2/access_token`;
	url += `?appid=${appid}`;
	url += `&secret=${secret}`;
	url += `&code=${code}`;
	url += `&grant_type=authorization_code`;
	request(url,function(error, response, body){
		if(error){
			throw error;
		}
		const params = JSON.parse(body);
		const {access_token, expires_in, refresh_token, openid, scope} = params;


		//获取基础的access_token，根据基础的access_token和openid获取用户信息
		let tokenURL = `https://api.weixin.qq.com/cgi-bin/token`;
		tokenURL += `?grant_type=client_credential`;
		tokenURL += `&appid=${appid}`;
		tokenURL += `&secret=${secret}`;
		request(tokenURL, function(error, response, body){
			if(error){
				throw error;
			}
			const {access_token:base_access_token, expires_in} = JSON.parse(body);

			let openidArr = [];
			let next_openid = '';

			// while(true){
			// 	let getUsersURL = `https://api.weixin.qq.com/cgi-bin/user/get`;
			// 	getUsersURL += `?access_token=${base_access_token}`;
			// 	getUsersURL += `&next_openid=${next_openid}`;
			// 	request(getUsersURL, function(error, response, body){
			// 		if(error){
			// 			throw error;
			// 		}
			// 		const resBody = JSON.parse(body);
			// 		openidArr = openidArr.concat(resBody.data.openid);
			// 		if(openidArr.length < resBody.total){
			// 			next_openid = resBody.next_openid;
			// 		} else {
			// 			break;
			// 		}
			// 	});
			// }
			// if(openidArr.indexOf(openid) !== -1){
			// 	res.render('subscribe');
			// }

			let getUsers = function(){
				let getUsersURL = `https://api.weixin.qq.com/cgi-bin/user/get`;
				getUsersURL += `?access_token=${base_access_token}`;
				getUsersURL += `&next_openid=${next_openid}`;
				request(getUsersURL, function(error, response, body){
					if(error){
						throw error;
					}
					const resBody = JSON.parse(body);
					openidArr = openidArr.concat(resBody.data.openid);
					console.log(JSON.stringify(resBody));
					if(openidArr.length < resBody.total){
						next_openid = resBody.next_openid;
						getUsers();
					} else {
						// 判断用户是否关注过公众号
						if(openidArr.indexOf(openid) === -1){
							res.json({code: '200', data: 0, message: 'not subscribe'});
						} else {
							// 获取用户信息start
							pool.getConnection(function(error, connection){
							if(error){
								throw error;
							}
							const queryOpenid = 'SELECT * FROM userOrder WHERE openid = ?';
							connection.query(queryOpenid, [openid], function(error, results, fields){
								if(error){
									throw error;
								}
								if(results.length === 0){
									// 用户第一次授权登录
									//根据网页授权access_token和openid获取用户的基本信息
									let infoURL = `https://api.weixin.qq.com/sns/userinfo`;
									infoURL += `?access_token=${access_token}`;
									infoURL += `&openid=${openid}`;
									infoURL += `&lang=zh_CN`;
									request(infoURL, function(err, response, body){
										if(err){
											throw err;
										}
										const params = JSON.parse(body);
										let {nickname} = params;
										// 如果用户的昵称超过5个字符，则从前往后截取5个字符，超出的部分舍弃
										if (nickname.length > 5) {
											nickname = nickname.substr(0,5);
										}
										const insertOpenid = `INSERT INTO userOrder SET ?`;
										const post = {openid, access_token, refresh_token, marking:nickname};
										connection.query(insertOpenid, post, function(error, results, fields){
											if(error){
												throw error;
											}
											connection.release();
											res.cookie('openid', openid, {maxAge: 7*24*60*60*1000});
											res.json({
												openid,
												marking:nickname,
											});
										});


										// res.json(JSON.parse(body));
									});

								} else {
									// 用户授权登陆过，但是授权过期了
									const orderid = results[0].order_id;
									connection.release();
									let marking = results[0].marking;
                                    // 如果用户的昵称超过5个字符，则从前往后截取5个字符，超出的部分舍弃
									if (marking.length > 5) {
										marking = marking.substr(0,5);
									}
									res.cookie('openid', openid, {maxAge: 7*24*60*60*1000});
									res.json({
										openid,
										marking,
										orderid,
									});
								}
							});
							// 获取用户信息end
						});
						}
						return;
					}
				});
			}
			getUsers();


			// // 根据基础的access_token和openid获取用户信息，invalid openid？？？
			// // 通过获取用户基本信息，根据subscribe字段来判断用户是否关注公众号
			// // 报错：{"errcode":40003,"errmsg":"invalid openid hint: [nEAGua0299hb10]"}
			// let infoURL = `https://api.weixin.qq.com/cgi-bin/user/info`;
			// infoURL += `?access_token=${base_access_token}`;
			// infoURL += `&openid=${openid}`;
			// infoURL += `?&lang=zh_CN`;
			// console.log(openid);
			// console.log(base_access_token);
			// request(infoURL, function(err, response, body){
			// 	if(err){
			// 		throw err;
			// 	}
			// 	console.log(body);
			// 	res.json({body:JSON.parse(body)});
			// });
		});

		// pool.getConnection(function(error, connection){
		// 	if(error){
		// 		throw error;
		// 	}
		// 	const queryOpenid = 'SELECT * FROM userOrder WHERE openid = ?';
		// 	connection.query(queryOpenid, [openid], function(error, results, fields){
		// 		if(error){
		// 			throw error;
		// 		}
		// 		if(results.length === 0){
		// 			// 用户第一次授权登录
		// 			//根据网页授权access_token和openid获取用户的基本信息
		// 			let infoURL = `https://api.weixin.qq.com/sns/userinfo`;
		// 			infoURL += `?access_token=${access_token}`;
		// 			infoURL += `&openid=${openid}`;
		// 			infoURL += `&lang=zh_CN`;
		// 			request(infoURL, function(err, response, body){
		// 				if(err){
		// 					throw err;
		// 				}
		// 				const params = JSON.parse(body);
		// 				const {nickname} = params;
		// 				const insertOpenid = `INSERT INTO userOrder SET ?`;
		// 				const post = {openid, access_token, refresh_token, marking:nickname};
		// 				connection.query(insertOpenid, post, function(error, results, fields){
		// 					if(error){
		// 						throw error;
		// 					}
		// 					connection.release();
		// 					res.cookie('openid', openid, {maxAge: 7*24*60*60*1000});
		// 					res.json({
		// 						openid,
		// 						marking:nickname,
		// 					});
		// 				});


		// 				// res.json(JSON.parse(body));
		// 			});

		// 		} else {
		// 			// 用户授权登陆过，但是授权过期了
		// 			const orderid = results[0].order_id;
		// 			connection.release();
		// 			const marking = results[0].marking;
		// 			res.cookie('openid', openid, {maxAge: 7*24*60*60*1000});
		// 			res.json({
		// 				openid,
		// 				marking,
		// 				orderid,
		// 			});
		// 		}
		// 	});
		// });
	});
});

router.get('/handleCode2', function(req, res, next){
	const params = URL.parse(req.url, true).query;
	const code = params.code;
	const appid = 'wx06c0a14577c208b3';
	const secret = 'c70fb7407b2f010933715a92837446e5';
	//根据code获取openid
	let url = `https://api.weixin.qq.com/sns/oauth2/access_token`;
	url += `?appid=${appid}`;
	url += `&secret=${secret}`;
	url += `&code=${code}`;
	url += `&grant_type=authorization_code`;
	let openid = '',
		access_token = '',
		refresh_token = '';
	request(url, function(error, response, body){
		if(error){
			throw error;
		}
		({access_token, openid, refresh_token} = JSON.parse(body));
		console.log(`openid:${openid}`);


		//获取基础的access_token，根据基础的access_token和openid获取用户信息
		let tokenURL = `https://api.weixin.qq.com/cgi-bin/token`;
		tokenURL += `?grant_type=client_credential`;
		tokenURL += `&appid=${appid}`;
		tokenURL += `&secret=${secret}`;
		let base_access_token = '',
			expires_in = '';
		request(tokenURL, function(error, response, body){
			if(error){
				throw error;
			}
			({access_token: base_access_token, expires_in} = JSON.parse(body));
			console.log(`base_access_token:${base_access_token}`);
			//根据基础的access_token和openid获取用户基本信息，无效？？？
			// let infoURL = `https://api.weixin.qq.com/cgi-bin/user/info`;
			// infoURL += `?access_token=${base_access_token}`;
			// infoURL += `&openid=${openid}`;
			// infoURL += `?&lang=zh_CN`;
			// request(infoURL, function(err, response, body){
			// 	if(err){
			// 		throw err;
			// 	}
			// 	console.log(JSON.parse(body));
			// 	res.json({body:JSON.parse(body)});
			// });

			// 将openid传给前端
			// 前端再调用/checkSubscribe接口，将openid再次传给后端
			// 根据这个字段获取用户信息，但是 无效？？？
			pool.getConnection(function(error, connection){
				if(error){
					throw error;
				}
				const insertOpenid = `INSERT INTO userOrder SET ?`;
				const post = {openid, access_token, refresh_token, base_access_token};
				connection.query(insertOpenid, post, function(error, results, fields){
					if(error){
						throw error;
					}
					connection.release();
					res.cookie('openid', openid, {maxAge: 7*24*60*60*1000});
					res.json({
						openid,
					});
				});
			});
			
		});
	});
	
});

module.exports = router;